﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.DataModel;
using System.Xml;
using SharedLib.XmlDataModel;

namespace Tracy.DataAccess
{
    public class FilterItemProvider<T> where T : XmlDataModel, IHasName, new()
    {
        protected XmlDocument doc = new XmlDocument();
        protected string _itemXPath;
        protected string _settingFile;
        //List<T> _items = new List<T>();

        public List<T> GetItems
        {
            get
            {
                List<T> rtn = new List<T>();
                foreach (XmlNode node in doc.SelectNodes(_itemXPath))
                {
                    T item = new T();
                    item.LoadXmlNode(node);
                    rtn.Add(item);
                }
                return rtn;
            }
        }

        //Dictionary<string, T> _indexName = new Dictionary<string, T>();
        public T GetItemByName(string name)
        {
            if (String.Equals(name, "*")) return new T() { Name = "*" };
            //if(_indexName.ContainsKey(name))
            //    return _indexName[name];
            //return null;
            XmlNode node = doc.SelectSingleNode(_itemXPath + String.Format("[@name='{0}']", name));
            if (node == null) return null;
            T item = new T();
            item.LoadXmlNode(node);
            return item;
        }

        public FilterItemProvider(string settingFile, string itemXPath)
        {
            _settingFile = settingFile;
            doc.Load(settingFile);
            _itemXPath = itemXPath;
            //foreach (XmlElement itemNode in doc.SelectNodes(itemXPath))
            //{
            //    T item = new T();
            //    item.LoadXmlNode(itemNode);
            //    Items.Add(item);
            //    _indexName.Add(item.Name, item);
            //}
        }
    }
}
